'use strict';

angular.module('afasApp')
  .controller('ContactsCtrl', ['$scope', 'Services', '$state', function ($scope, Services, $state) {

    $scope.contacts = [];
    $scope.contactNew = {};
    $scope.contactTypes = [];
    $scope.countries = [];
    $scope.provinces = [];
    $scope.cities = [];

    Services.getItems($scope.CONTACTTYPE_URL)
    .then(function(results){
      $scope.contactTypes = results.data;
    });

    Services.getItems('countries')
    .then(function(results){
      $scope.countries = results.data;
    });

    Services.getItems('cities')
    .then(function(results){
      $scope.cities = results.data;
    });

    $scope.$watch('contactNew.CountryId', function(){
      Services.getItems('provinces')
      .then(function(results){
        $scope.provinces = results.data;
      });
    });

    function applyRemoteData( newData ) {
      $scope.contacts = newData;
    }

    function loadRemoteData() {
      Services.getItems('contacts')
      .then(function( results ) {
        applyRemoteData( results.data );
      });
    }

    loadRemoteData();

    $scope.addContact = function () {
      Services.add('contacts', $scope.contactNew)
      .then(function(results){
        console.log(results);
        $scope.contactNew = {};
        $state.go( 'contacts.list' );
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
      // Contacts.addContact($scope.contactTypeNew);
    };

    $scope.deleteContact = function (contact) {
      Services.delete('contacts', contact)
      .then(function(results){
        console.log(results);
        loadRemoteData();
      });
      // Contacts.deleteContact(contactType);
    };
  }]).controller('ContactCtrl', ['$scope', 'Services', '$state', '$stateParams', function ($scope, Services, $state, $stateParams) {

    $scope.currentContact = {};
    $scope.currentID = $stateParams.id;

    Services.getItem('contacts', $stateParams.id)
    .then(function(results){
      $scope.currentContact = results.data;
    });
    // $scope.currentContact =Contacts.getContact($stateParams.id);

    $scope.updateContact = function () {
      Services.update('contacts', $scope.currentContact, $scope.currentID)
      .then(function(results){
        console.log(results);
        $state.go( 'contacts.show', {id: $scope.currentID} );
      });
      // ContactTypes.updateContactType($scope.currentContactType, $scope.currentID);
    };
  }]);